const { Controller } = require('egg');
const { CozeAPI, COZE_CN_BASE_URL } = require('@coze/api');
const {getBotInfo} = require("../api/coze");
const {getAgentToken} = require("../api/common");

class AgentController extends Controller {
    /**
     * 根据AgentID获取智能体信息，不从Coze服务器上
     */
    async getAgentInfoByAgentId(){
        const { ctx, app } = this;
        const {agent_id} = ctx.request.query;
        if (!agent_id) {
            ctx.body = {
                success: false,
                message: '请选择智能体'
            };
        }
        // 根据ID获取botID
        const agentInfo = await app.mysql.get('agents',{
            id:agent_id
        });
        if (!agentInfo) {
            ctx.body = {
                success: false,
            }
        }
        ctx.body = {
            success: true,
            data: agentInfo
        };

    }

    /**
     * 设置智能体是否公开
     */
    async setAgentIsPublic(){
        const { ctx, app } = this;
        const {agent_id,is_public} = ctx.request.body;
        if (!agent_id) {
            ctx.body = {
                success: false,
                message: '请选择智能体'
            };
        }
        const res = await app.mysql.update('agents',{

                id:parseInt(agent_id),
                is_public:is_public

        });
        if (res){
            ctx.body = {
                success: true,
                message: '设置成功'
            };
        }
        else{
            ctx.body = {
                success: false,
                message: '设置失败'
            };
        }
    }

    /**
     * 同步智能体信息
     */
    async syncAgentInfo(){
        const { ctx, app } = this;
        const {agent_id} = ctx.request.query;
        if (!agent_id) {
            ctx.body = {
                success: false,
                message: '请选择智能体'
            };
        }
        // 根据ID获取botID
        const agentInfo = await app.mysql.get('agents',{
            id:agent_id
        });
        if (!agentInfo) {
            ctx.body = {
                success: false,
                message: '找不到该智能体'
            };
        }

        const client = new CozeAPI({
            baseURL: COZE_CN_BASE_URL,
            token: agentInfo.access_token,
        });
        const result = await getBotInfo(agentInfo.bot_id,agentInfo.access_token)
        await app.mysql.update('agents',{
            id:agentInfo.id,
            bot_name:result.data.name,
            description:result.data.description,
            icon_url:result.data.icon_url,
            update_time:result.data.update_time,
        })
        ctx.body = {
            success: true,
            data: {
                id:agentInfo.id,
                bot_name:result.data.name,
                description:result.data.description,
                icon_url:result.data.icon_url,
                update_time:result.data.update_time,
            }
        };
    }


    /**
     * 获取全部公开的智能体列表
     */
    async getAllPublicAgentList(){
        const { ctx, app } = this;
        const agentList = await app.mysql.select('agents',{
            where:{
                is_public:1,
            },
        })
        for (const agentListElement of agentList) {
            agentListElement['chats_number'] = await app.mysql.count('conversations',{
                bot_id:agentListElement.bot_id
            })
            delete agentListElement.privateKey;
            delete agentListElement.secret_token;
            delete agentListElement.fingerprint;
        }
        ctx.body = {
            success: true,
            data: agentList
        };
    }

    /**
     *  获取我的智能体列表
     */
    async getMyAgentList(){
        const { ctx, app } = this;
        const {page,pageSize} = ctx.query;
        const agentList = await app.mysql.select('agents',{
            where:{
                user_id:ctx.currentUser.id,
            },
        })
        for (const agentListElement of agentList) {
            agentListElement['chats_number'] = await app.mysql.count('conversations',{
                bot_id:agentListElement.bot_id
            })
            delete agentListElement.privateKey;
            delete agentListElement.secret_token;
            delete agentListElement.fingerprint;
        }
        ctx.body = {
            success: true,
            data: agentList
        };
    }


    /**
     * 发布智能体
     */
    async publicAgent(){
        const { ctx, app } = this;
        const {bot_id,is_public} = ctx.request.body;
        if (!bot_id) {
            ctx.body = {
                success: false,
                message: '请选择智能体'
            };
        }
        const client = new CozeAPI({
            baseURL: COZE_CN_BASE_URL,
            token: ctx.currentUser.coze_access_token,
        });

        const agent = await client.bots.retrieve({bot_id: bot_id});
        // 数据库是否存在
        const agentInfo = await app.mysql.get('agents',{
            bot_id:bot_id
        });
        if (agentInfo) {
            // 更新
            await app.mysql.update('agents',{
                id:agentInfo.id,
                bot_name:agent.name,
                description:agent.description,
                icon_url:agent.icon_url,
                is_public:is_public || 1,
                user_id:ctx.currentUser.id,
                fingerprint:ctx.currentUser?.coze_fingerprint||'',
                privateKey:ctx.currentUser?.coze_privateKey||'',
                app_id:ctx.currentUser?.coze_app_id||'',
                update_time:agent.update_time,
                access_token:ctx.currentUser.coze_access_token,
            })
            ctx.body = {
                success: true,
                message: '更新成功'
            };
        }else{
            await app.mysql.insert('agents',{
                bot_id:bot_id,
                bot_name:agent.name,
                description:agent.description,
                icon_url:agent.icon_url,
                is_public:is_public || 1,
                access_token:ctx.currentUser.coze_access_token,
                user_id:ctx.currentUser.id,
                fingerprint:ctx.currentUser?.coze_fingerprint||'',
                privateKey:ctx.currentUser?.coze_privateKey||'',
                app_id:ctx.currentUser?.coze_app_id||'',
                create_time:agent.create_time,
                update_time:agent.update_time,
                publish_time:new Date(),
            })
            ctx.body = {
                success: true,
                message: '发布成功'
            };
        }

    }


}
module.exports = AgentController;